package org.atlas.framework.helper;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.atlas.framework.ds.impl.DefaultDataSourceFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * 数据库操作
 *
 * Created by suxinjie on 2017/3/5.
 */
public class DataBaseHelper {
    private static final Logger logger = LoggerFactory.getLogger(DataBaseHelper.class);

    // FIXME 还没考虑好扩展方案,暂时先用DefaultDataSourceFactory
    private static final BasicDataSource DATA_SOURCE;
    private static final QueryRunner QUERY_RUNNER;

    static {
        DATA_SOURCE = (BasicDataSource) new DefaultDataSourceFactory().getDataSource();
        QUERY_RUNNER = new QueryRunner(DATA_SOURCE);
    }

    private static final ThreadLocal<Connection> CONNECTION_HOLDER = new ThreadLocal<>();

    /**
     * 获取数据库链接
     */
    public static Connection getConnection() {
        Connection conn = CONNECTION_HOLDER.get();
        if (conn == null) {
            try {
                conn = DATA_SOURCE.getConnection();
            } catch (SQLException e) {
                logger.error("get connection failure", e);
                throw new RuntimeException(e);
            } finally {
                CONNECTION_HOLDER.set(conn);
            }
        }

        return conn;
    }

    /**
     * 关闭数据库链接
     */
    public static void closeConnection() {
        Connection conn = CONNECTION_HOLDER.get();
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                logger.error("close connection failure", e);
                throw new RuntimeException(e);
            } finally {
                CONNECTION_HOLDER.remove();
            }

        }
    }

    /**
     * 查询实体列表
     *
     * @param entityClass  实体类
     * @param sql          查询sql
     * @param params       sql参数
     * @param <T>          实体类
     * @return             实体列表
     */
    public static <T> List<T> queryEntityList(Class<T> entityClass, String sql, Object... params) {
        List<T> entityList;

        try {
            entityList = QUERY_RUNNER.query(getConnection(), sql, new BeanListHandler<T>(entityClass), params);
        } catch (Exception e) {
            logger.error("query entity list failure", e);
            throw new RuntimeException(e);
        } finally {
            closeConnection();
        }

        return entityList;
    }

    /**
     * 查询单个实体
     *
     * @param entityClass  实体类
     * @param sql          查询sql
     * @param params       sql参数
     * @param <T>          实体类
     * @return             单个实体
     */
    public static <T> T queryEntity(Class<T> entityClass, String sql, String... params) {
        T entity;

        try {
            entity = QUERY_RUNNER.query(getConnection(), sql, new BeanHandler<T>(entityClass), params);
        } catch (SQLException e) {
            logger.error("query entity failure", e);
            throw new RuntimeException(e);
        } finally {
            closeConnection();
        }

        return entity;
    }

    /**
     * 执行查询
     *
     * @param sql       查询语句
     * @param params    查询参数
     * @return
     */
    public static List<Map<String, Object>> executeQuery(String sql, Object... params) {
        List<Map<String, Object>> result;

        try {
            result = QUERY_RUNNER.query(getConnection(), sql, new MapListHandler(), params);
        } catch (SQLException e) {
            logger.error("execute query failure", e);
            throw new RuntimeException(e);
        } finally {
            closeConnection();
        }

        return result;
    }

    /**
     * 执行更新
     *
     * @param sql       查询语句
     * @param params    查询参数
     * @return          影响行数
     */
    public static int executeUpdate(String sql, Object... params) {
        int rows = 0;
        try {
            rows = QUERY_RUNNER.update(getConnection(), sql, params);
        } catch (SQLException e) {
            logger.error("execute update failure", e);
            throw new RuntimeException(e);
        } finally {
            closeConnection();
        }

        return rows;
    }


    //TODO 增删该涉及到字段转换,稍后实现


}
